package net.sppan.base.controller.admin;

import net.sppan.base.entity.Resource;
import net.sppan.base.entity.Role;
import net.sppan.base.entity.User;
import net.sppan.base.service.IResourceService;
import net.sppan.base.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import net.sppan.base.controller.BaseController;

import java.util.*;

@Controller
public class AdminIndexController extends BaseController{

	@Autowired
	private IResourceService resourceService;

	@Autowired
	private IUserService userService;

	@RequestMapping(value ={"/admin/","/admin/index"})
	public String index(ModelMap map){

		Set<Resource> resources=new HashSet<Resource>();
		Map<String, List<Resource>> resourceListMap = new HashMap<String, List<Resource>>();

		String userName=(String)request.getSession().getAttribute("cur_user_name");

		int i=0;
		if(userName.equalsIgnoreCase("admin")){
			resources.addAll(resourceService.findAll());
		}
		else {
			User curUser = userService.findByUserName(userName);

			Set<Role> roles = curUser.getRoles();

			for (Role r : roles) {
				resources.addAll(r.getResources());
			}
		}

		for(Resource restop: resources)
			if (restop.getParent() == null) {
				List<Resource> resDict = new ArrayList<Resource>();


				for (Resource res_level2 : resources) {
					if (res_level2.getParent() == restop) {
						resDict.add(res_level2);
					}
				}
				resourceListMap.put(restop.getDescription(), resDict);
			}

		map.put("menus",resourceListMap);
		
		return "admin/index";
	}
	
	@RequestMapping(value = {"/admin/welcome"})
	public String welcome(){
		
		return "admin/welcome";
	}
}
